package com.yyk.yykywd.util;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

/**
 * 保存图片到文件
 */
public class FileUtils {
    public static File saveBitmapToFile(Bitmap bitmap) {
        //保存图片
        File file = getFile();
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 80, fos);
            fos.flush();
            fos.close();
        } catch (java.io.IOException e) {
            e.printStackTrace();
        }

        return file;
    }

    public static File getFile() {
        return getFile(System.currentTimeMillis() + ".jpg");
    }

    public static Uri getUri() {
        return Uri.fromFile(getFile());
    }

    public static File getFile(String fileName) {
        File appDir = new File(Environment.getExternalStorageDirectory(), "yykywd");
        if (!appDir.exists()) {
            appDir.mkdirs();
        }
        return new File(appDir, fileName);
    }

    /**
     * 截取指定View为图片
     *
     * @param view
     */
    public static Bitmap captureView(View view) {
        Bitmap bm = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
        view.draw(new Canvas(bm));
        return bm;
    }

    public static void insertImage(Context context, File file) {
        //把文件插入图库
        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), file.getName(), null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        //最后通知图库进行更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getPath())));
    }
}
